<?php

/**
 * 
 */

class NfileScript extends ScriptBase {

	private $api = null;

	/**
	 * 构造函数
	 *
	 */
	public function __construct(){
		$this->api = n_api("nfile");
	}
	
	
	public function sync(){
		
		$cHandle = n_api('nconfig');
		$conf = $cHandle->pluginsGet("nfile",'copynum');
		$copynum = $conf['value'];
		
		
		$muList = $this->api->getMu();
		//print_r($muList);
		//exit;
		$start = 0;
		$perpage = 1000;
		
		while(true){
			$ids = array();
			
			$mysql = n_api("mysql")->db001;
			$list = $mysql->select("select id from nfile_main limit {$start},{$perpage}");
			if(empty($list)){
				break;
			}
			foreach($list as $key=>$val){
				$ids[] = $val['id'];
			}
			$start += $perpage;
			$slist = $mysql->select("select a.id,count(*) as total from nfile_main as a left join nfile_copy as b on a.id=b.main_id where a.id in(".implode(',', $ids).") group by a.id having total<{$copynum}");

			if(!empty($slist)){
				foreach($slist as $key=>$val){
					$copylist= $mysql->selectIndex("select mu_id from nfile_copy where main_id={$val['id']}",'mu_id');
					$mutmp = array_diff(array_keys($muList),array_keys($copylist));
					shuffle($mutmp);
					//print_r(array_keys($muList));
					
					$snum = $copynum - count($copylist);
					for($i=0;$i<$snum;$i++){
						$mid = array_pop($mutmp);
						//echo $mainId.'=='.$mid."\n";
						//$mainId,$ip,$sfile,$dfile
						$muinfo = $muList[$mid];
						$filename = $this->api->getFiledir($val['id']);
						$sfile = $muList[array_rand($copylist)]['dir'].$filename;
						$dfile = $muinfo['dir'].$filename;
						
						$this->api->copy($val['id'],$muinfo['ip'],$sfile,$dfile);
						$mysql->insert("nfile_copy",array('mu_id'=>$muinfo['id'],'main_id'=>$val['id'],'ctime'=>N_NOW));
					}
				}
			}
		}
	}
	
}


?>